package com.webgis.utils;

import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Component;

import com.webgis.pojo.Szry;

@Component
public class WFSGetFeatureGenerator {
    public String createWFSGetFeature(List<Szry> persons) {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("wfs:FeatureCollection")
               .addNamespace("wfs", "http://www.opengis.net/wfs")
               .addNamespace("test", "http://localhost:8888/test")
               .addNamespace("gml", "http://www.opengis.net/gml")
               .addNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance")
               .addAttribute("xsi:schemaLocation",
                        "http://localhost:8888/test http://localhost:8888/wfs?service=WFS&version=1.0.0&request=DescribeFeatureType&typeName=test:szry " +
                                "http://www.opengis.net/wfs http://localhost:8080/geoserver/schemas/wfs/1.0.0/WFS-basic.xsd");

        Element boundedBy = root.addElement("gml:boundedBy");
        boundedBy.addElement("gml:null").setText("unknown");

        for (Szry person : persons) {
            Element featureMember = root.addElement("gml:featureMember");
            Element szryElement = featureMember.addElement("test:szry")
                   .addAttribute("fid", "szry." + (persons.indexOf(person) + 1));

            addNonNullElement(szryElement, "test:id", person.getId());
            addNonNullElement(szryElement, "test:objectid", person.getObjectid());
            // 其他属性字段添加...

            Element geomElement = szryElement.addElement("test:geom");
            Element pointElement = geomElement.addElement("gml:Point")
                   .addAttribute("srsName", "http://www.opengis.net/gml/srs/epsg.xml#4326");
            addCoordinates(pointElement, person.getLongitude(), person.getLatitude());
        }

        return document.asXML();
    }

    private void addNonNullElement(Element parent, String name, Object value) {
        if (value != null) {
            parent.addElement(name).setText(value.toString());
        }
    }

    private void addCoordinates(Element parent, Object longitude, Object latitude) {
        if (longitude != null && latitude != null) {
            Element coordinatesElement = parent.addElement("gml:coordinates")
                   .addAttribute("decimal", ".")
                   .addAttribute("cs", ",")
                   .addAttribute("ts", " ");
            coordinatesElement.setText(longitude.toString() + "," + latitude.toString());
        }
    }
}
